package com.sunshine.lnuplus.internet

import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.utils.LoadScoreUtils
import okhttp3.*
import org.jsoup.Jsoup
import java.io.IOException

/**
 * Created by sunshine on 2020/3/13
 */

class LoadScore(
    private val user: String,
    private val password: String,
    private val loginCallBack: LoginCallBack
) {

    init {
        toLoad()
    }

    private fun toLoad(){
        val okHttpClient = OkHttpClient()
            .newBuilder()
            .followRedirects(false)
            .build()
        val requestBody = FormBody.Builder()
            .add("stuid", user)
            .add("pwd", password)
            .build()
        val request = Request.Builder()
            .url("http://jwgl.lnu.edu.cn/pls/wwwbks/bks_login2.login")
            .post(requestBody)
            .build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                loginCallBack.onFail("没有网络连接")
            }

            override fun onResponse(call: Call, response: Response) {
                val headers = response.headers
                var cookie = ""
                headers.forEach {
                    if(it.first == "Set-Cookie"){
                        cookie = it.second
                    }
                }
                if(cookie.isEmpty()){
                    loginCallBack.onFail("账号或密码错误")
                }else{
                    val okHttpClient2 = OkHttpClient()
                        .newBuilder()
                        .build()
                    val request2 = Request.Builder()
                        .url("http://jwgl.lnu.edu.cn/pls/wwwbks/bkscjcx.curscopre")
                        .header("Cookie",cookie)
                        .build()
                    okHttpClient2.newCall(request2).enqueue(object : Callback {
                        override fun onFailure(call: Call, e: IOException) {
                            loginCallBack.onFail("成绩解析失败")
                        }

                        override fun onResponse(call: Call, response: Response) {
                            val document = Jsoup.parse(response.body?.string())
                            val timetable = document.select("td[bgcolor=\"#EAE2F3\"]")
                            LoadScoreUtils.init(timetable, loginCallBack, user)
                        }
                    })
                }
            }
        })
    }
}